package com.projiect.dao.impl;

import com.projiect.bean.StudentBean;
import com.projiect.dao.IClassBeanDao;
import com.projiect.dao.IStudentBeanDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class IStudentBeanDaoImpl extends BaseDao implements IStudentBeanDao {
    IClassBeanDao iClassBeanDao = new IClassBeanDaoImpl();

    @Override
    public void createStudentTable() {
        this.setCon();
        try {
            ps = con.prepareStatement("CREATE TABLE t_student(" +
                    "pk_studentId INT PRIMARY KEY AUTO_INCREMENT," +
                    "s_name VARCHAR(20)," +
                    "fk_classId int" +
                    ");");
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }
    }

    @Override
    public List<StudentBean> findAllStudent() {
        List<StudentBean> list = new ArrayList<>();
        this.setCon();
        try {
            ps = con.prepareStatement("select * from t_student s,t_class c where s.fk_classId=c.pk_classId ");
            rs = ps.executeQuery();
            while (rs.next()) {
                list.add(cv());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }
        return list;
    }

    @Override
    public void addStudent(StudentBean student) {
        this.setCon();
        try {
            ps = con.prepareStatement("insert into t_student(s_name,fk_classId)values (?,?)");
            ps.setObject(1,student.getName());
            ps.setObject(2,student.getClassBean().getId());
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }

    }

    public StudentBean cv() throws SQLException {
        StudentBean student = new StudentBean();
        student.setId(rs.getInt("pk_studentId"));
        student.setName(rs.getString("s_name"));
        student.setClassBean(iClassBeanDao.findClassById(rs.getInt("fk_classId")));
        return student;
    }
}
